package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.VipCard;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IVipCardService;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.http.HttpClient;

import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;

/**
 * @author by Lwh on 2018/3/13.
 */
@Api(value = "vipCard", description = "一卡通信息", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/vipCard")
public class VipCardController {

    private static Logger log = Logger.getLogger(VipCardController.class);

    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private IVipCardService iVipCardService;

    /**
     * 根据电话号码,查询一卡通信息
     * @param phoneNumber 电话号码
     * @return 一卡通信息
     */
    @RequestMapping("/getVipCardInfo")
    @ApiOperation(value = "从代收平台获取一卡通列表")
    public ResponseEntity getVipCardInfo(@RequestParam String phoneNumber) {
        log.info("手机号：" + phoneNumber);
        Map returnMap = new HashMap();
        Map<String, String> params = Maps.newHashMap();
        if (StringUtil.isEmpty(phoneNumber)) {
            return new ResponseEntity<>(getResultMap("101",null,"参数phoneNumber不能为空",false,null,null), HttpStatus.OK);
        }
        //根据电话号码,查询一卡通信息
        params.put("phoneNumber", phoneNumber);
        String url = StaticUtil.VIP_CARD_INFO_URL;
        try {
            log.info("参数：" + params);
            String retStr = HttpClientUtils.post(url, params, null, 10000, 10000);
            returnMap = JSON.parseObject(retStr);
            return new ResponseEntity<>(returnMap, HttpStatus.OK);
        } catch (Exception e) {
            log.error("根据电话号码,查询一卡通信息失败",e);
            return new ResponseEntity<>(getResultMap("101",null,e.getMessage(),false,null,null), HttpStatus.OK);
        }
    }
    //    根据电话号码,查询一卡通信息JSON格式
//    {
//        "result": true,
//            "code": 100,
//            "resultId": null,
//            "message": "成功",
//            "interFaceName": "queryByPhoneNumber",
//            "resultObject": [
//        {
//            "phoneNumber": "13313609959",
//                "createTime": "2018-03-07T14:17:34",
//                "cityCode": "2301",
//                "provinceCode": "23",
//                "cardCode": "072666",
//                "tableId": 40658,
//                "page": 1,
//                "version": null
//        }
//    ]
//    }

    /**
     * 返回一卡通明细
     * @param page 页码
     * @param rows 行数
     * @param oneCardNo 一卡通号
     * @param phone 电话号
     * @param startDate 发款日期-开始
     * @param endDate 发款日期-结束
     * @return 一卡通明细信息
     */
    @ApiOperation(value = "从代收平台获取代收明细")
    @RequestMapping("/getVipCardDetails")
    public ResponseEntity getVipCardDetails(@RequestParam String page,
                                            @RequestParam String rows,
                                            @RequestParam String oneCardNo,
                                            @RequestParam String phone,
                                            @RequestParam String startDate,
                                            @RequestParam String endDate){
        Map returnMap = new HashMap();
        Map<String,String> params= Maps.newHashMap();
        if(StringUtil.isEmpty(page)){
            return new ResponseEntity<>(getResultMap("101",null,"参数page不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(rows)){
            return new ResponseEntity<>(getResultMap("101",null,"参数rows不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(oneCardNo)){
            return new ResponseEntity<>(getResultMap("101",null,"参数oneCardNo不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(phone)){
            return new ResponseEntity<>(getResultMap("101",null,"参数phone不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(startDate)){
            startDate = DateUtil.getMonthChange(new Date(),-3,null);
            //return new ResponseEntity<>(getResultMap("101",null,"参数startDate不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(endDate)){
            endDate = DateUtil.turnDateToString(new Date(),"yyyy-MM-dd");
            //return new ResponseEntity<>(getResultMap("101",null,"参数endDate不能为空",false,null,null), HttpStatus.OK);
        }
        params.put("page",page);
        params.put("rows",rows);
        params.put("oneCardNo",oneCardNo);
        params.put("phone",phone);
        params.put("startDate",startDate);
        params.put("endDate",endDate);
        String url = StaticUtil.VIP_CARD_DETAILS_URL;
        try {
            log.info("参数：" + params);
            String retStr = HttpClientUtils.post(url, params, null, 10000, 10000);
            returnMap = JSON.parseObject(retStr);
            return new ResponseEntity<>(returnMap, HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询一卡通代收明细失败",e);
            return new ResponseEntity<>(getResultMap("101",null,e.getMessage(),false,null,null), HttpStatus.OK);
        }
    }
    //    返回内容一卡通明细JSON格式
//    {
//        "code": 100,
//            "interFaceName": "代收款款查询",
//            "message": "成功",
//            "result": true,
//            "resultId": null,
//            "resultObject": [
//        {
//            "_parentId": null,
//                "cardNo": "6222023500027078431",
//                "collectPerson": "张静",
//                "collectPhone": "13313609959",
//                "companyName": "hrbcdwl",
//                "countNo": null,
//                "cutGoodsFreight": 0,
//                "date": null,
//                "delayFee": 0,
//                "diqu": "哈尔滨",
//                "diquNum": "2301",
//                "endMan": "王喜才",
//                "endManPhone": "18104597730",
//                "fee": 4,
//                "fid": 11292875,
//                "fkDate": "2014-04-30T09:40:38",
//                "goodsPrice": 703,
//                "gsChinese": "大庆诚达物流有限公司",
//                "hh": "",
//                "hkDate": "2014-04-20T00:00:00",
//                "kpDate": "2014-04-19T00:00:00",
//                "lostFee": 0,
//                "manual": "",
//                "nowTime": "2015-03-16T11:52:23",
//                "oneCardNo": "072666",
//                "oughtGoodsPrice": 699,
//                "page": 1,
//                "ph": "HHR51871",
//                "refuseGoodsPrice": 0,
//                "sheng": "黑龙江",
//                "shengNum": "23",
//                "state": "closed",
//                "textFee": 0,
//                "version": null
//        },
//        {
//            "_parentId": null,
//                "cardNo": "6222023500027078431",
//                "collectPerson": "张静",
//                "collectPhone": "13313609959",
//                "companyName": "hrbcdwl",
//                "countNo": null,
//                "cutGoodsFreight": 0,
//                "date": null,
//                "delayFee": 0,
//                "diqu": "哈尔滨",
//                "diquNum": "2301",
//                "endMan": "高明",
//                "endManPhone": "13836785758",
//                "fee": 4,
//                "fid": 11292825,
//                "fkDate": "2014-05-05T13:31:22",
//                "goodsPrice": 1703,
//                "gsChinese": "大庆诚达物流有限公司",
//                "hh": "",
//                "hkDate": "2014-04-30T00:00:00",
//                "kpDate": "2014-04-28T00:00:00",
//                "lostFee": 0,
//                "manual": "00002585",
//                "nowTime": "2015-03-16T11:52:15",
//                "oneCardNo": "072666",
//                "oughtGoodsPrice": 1699,
//                "page": 1,
//                "ph": "HHR53413",
//                "refuseGoodsPrice": 0,
//                "sheng": "黑龙江",
//                "shengNum": "23",
//                "state": "closed",
//                "textFee": 0,
//                "version": null
//        },
//        {
//            "_parentId": null,
//                "cardNo": "6222023500027078431",
//                "collectPerson": "张静",
//                "collectPhone": "13313609959",
//                "companyName": "hrbcdwl",
//                "countNo": null,
//                "cutGoodsFreight": 0,
//                "date": null,
//                "delayFee": 0,
//                "diqu": "哈尔滨",
//                "diquNum": "2301",
//                "endMan": "李科",
//                "endManPhone": "13846295756",
//                "fee": 4,
//                "fid": 11292830,
//                "fkDate": "2014-05-05T13:31:22",
//                "goodsPrice": 4703,
//                "gsChinese": "大庆诚达物流有限公司",
//                "hh": "",
//                "hkDate": "2014-05-03T00:00:00",
//                "kpDate": "2014-04-30T00:00:00",
//                "lostFee": 0,
//                "manual": "",
//                "nowTime": "2015-03-16T11:52:16",
//                "oneCardNo": "072666",
//                "oughtGoodsPrice": 4699,
//                "page": 1,
//                "ph": "HHR53980",
//                "refuseGoodsPrice": 0,
//                "sheng": "黑龙江",
//                "shengNum": "23",
//                "state": "closed",
//                "textFee": 0,
//                "version": null
//        },
//        {
//            "_parentId": null,
//                "cardNo": "6222023500027078431",
//                "collectPerson": "张静",
//                "collectPhone": "13313609959",
//                "companyName": "hrbcdwl",
//                "countNo": null,
//                "cutGoodsFreight": 0,
//                "date": null,
//                "delayFee": 0,
//                "diqu": "哈尔滨",
//                "diquNum": "2301",
//                "endMan": "高明",
//                "endManPhone": "13836785758",
//                "fee": 4,
//                "fid": 11292835,
//                "fkDate": "2014-05-17T16:03:43",
//                "goodsPrice": 3623,
//                "gsChinese": "大庆诚达物流有限公司",
//                "hh": "",
//                "hkDate": "2014-05-01T00:00:00",
//                "kpDate": "2014-04-30T00:00:00",
//                "lostFee": 0,
//                "manual": "",
//                "nowTime": "2015-03-16T11:52:17",
//                "oneCardNo": "072666",
//                "oughtGoodsPrice": 3619,
//                "page": 1,
//                "ph": "HHR53981",
//                "refuseGoodsPrice": 0,
//                "sheng": "黑龙江",
//                "shengNum": "23",
//                "state": "closed",
//                "textFee": 0,
//                "version": null
//        }
//    ]
//    }

    public Map getResultMap(String code,String interFaceName,String message,boolean result,String resultId,String resultObject){
        Map returnMap = new HashMap();
        returnMap.put("code",code);
        returnMap.put("interFaceName",interFaceName);
        returnMap.put("message",message);
        returnMap.put("result",result);
        returnMap.put("resultId",resultId);
        returnMap.put("resultObject",resultObject);
        return returnMap;
    }

    /**
     * 根据金融代码和一卡通号查询代收明细
     *
     * @param currentPage 页码
     * @param pageSize 行数
     * @param vipNo 一卡通号
     * @param code 金融代码
     * @param orderStartDate 开票日期-开始
     * @param orderEndDate 开票日期-结束
     * @param exposureStartDate 发款日期-开始
     * @param exposureEndDate 发款日期-结束
     * @return 一卡通明细信息
     */
    @RequestMapping(value = "/getVipCardDetailsBSOrF6", method = RequestMethod.POST)
    @ApiOperation(value = "根据金融代码和一卡通号查询代收明细")
    public ResponseEntity getVipCardDetailsBSOrF6(@RequestParam String currentPage,
                                            @RequestParam String pageSize,
                                            @RequestParam String vipNo,
                                            @RequestParam String code,
                                            @RequestParam String orderStartDate,
                                            @RequestParam String orderEndDate,
                                            @RequestParam String exposureStartDate,
                                            @RequestParam String exposureEndDate){


        final Map<String,String> params= Maps.newHashMap();
        if(StringUtil.isEmpty(currentPage)){
            return new ResponseEntity<>(getResultMap("101",null,"当前页数不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(pageSize)){
            return new ResponseEntity<>(getResultMap("101",null,"每页个数不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(vipNo)){
            return new ResponseEntity<>(getResultMap("101",null,"一卡通号不能为空",false,null,null), HttpStatus.OK);
        }
        if(StringUtil.isEmpty(code)){
            return new ResponseEntity<>(getResultMap("101",null,"金融代码不能为空",false,null,null), HttpStatus.OK);
        }
        params.put("currentPage",currentPage);
        params.put("pageSize",pageSize);
        params.put("vipNo",vipNo);
        params.put("orderStartDate",orderStartDate);
        params.put("orderEndDate",orderEndDate);
        params.put("exposureStartDate",exposureStartDate);
        params.put("exposureEndDate",exposureEndDate);

        try {
            Company company = iCompanyInfoService.getCompanyByCode(code);
            if(StringUtil.isEmpty(company.getUrl())){
                return new ResponseEntity<>(getResultMap("101",null,"未设置租户信息",false,null,null), HttpStatus.OK);
            }
            String url = company.getUrl()+"/orderBaseInfo/getDeliveryRecordsByVipCard?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
            log.info("一卡通详细请求路径：" + url+"&param="+ JSONObject.toJSONString(params));
            //String result = HttpUtil.post(url,new HashMap<String, String>(){{put("param",JSONObject.toJSONString(params));}});
            String result = HttpClientUtils.post( url+"&param="+ JSONObject.toJSONString(params), null, setHeader(), 20000, 20000);
            log.info("一卡通详细返回结果：" + result);
            if(StringUtil.isNotEmpty(result)){
                ResultModel model = JSON.parseObject(result,ResultModel.class);
                if(200 == model.getCode()){
                    if("SUCCESS".equals(model.getMsg())){
                        return new ResponseEntity<>(ResultModel.ok(model.getContent()), HttpStatus.OK);
                    }
                }else{
                    throw new Exception("从F6或BS服务端获取代收明细失败！" + model.getMsg());
                }
            }else{
                throw new Exception("请求F6或BS服务端失败或无返回值！");
            }
        } catch (JSONException e) {
            log.error("请求F6或BS服务端出错，请联系管理员！",e);
            return new ResponseEntity<>(ResultModel.error("请求F6或BS服务端出错，请联系管理员！"), HttpStatus.OK);
        }  catch (SocketTimeoutException e) {
            log.error("请求F6或BS服务端超时，请联系管理员！",e);
            return new ResponseEntity<>(ResultModel.error("请求F6或BS服务端超时，请联系管理员！"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("服务端出错！",e);
            return new ResponseEntity<>(ResultModel.error("服务端出错！"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
    }


    /**
     * 根据电话号码,查询一卡通信息
     * @param phoneNumber 电话号码
     * @return 一卡通信息
     */
    @RequestMapping("/getVipCardList")
    @ApiOperation(value = "根据手机获取一卡通列表")
    public ResponseEntity getVipCardList(@RequestParam String phoneNumber) {
        log.info("手机号：" + phoneNumber);
        Map returnMap = new HashMap();
        Map<String, String> params = Maps.newHashMap();
        if (StringUtil.isEmpty(phoneNumber)) {
            return new ResponseEntity<>(getResultMap("101",null,"参数phoneNumber不能为空",false,null,null), HttpStatus.OK);
        }
        //根据电话号码,查询一卡通信息
        List<VipCard> resultList=null;
        try {
            log.info("参数：" + phoneNumber);
            VipCard vipCard = new VipCard();
            vipCard.setMobile(phoneNumber);
            resultList= iVipCardService.select(vipCard);
            return new ResponseEntity<>(JSON.toJSON(resultList).toString(), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询一卡通信息失败",e);
            return new ResponseEntity<>(getResultMap("101",null,e.getMessage(),false,null,null), HttpStatus.OK);
        }
    }
}